<script setup>
import { ref, onMounted } from 'vue'
import easyapi from '../api'
import { ElMessage, ElMessageBox, pageHeaderEmits } from 'element-plus'
//定义绑定的数据
const tableData = ref([]);
//控制新增信息窗口是否显示
const addWinVisible = ref(false);
//新增数据绑定对象
const addObject = ref({});
//控制新增信息窗口是否显示
const editWinVisible = ref(false);
//编辑数据绑定对象
const editObject = ref({});
//记录编辑数据的下标
var editIndex = -1;
//分页的总页数
const total = ref(100)
//查询数据输入框的绑定对象
const checkObj = ref({
    size: 3,
    page: 1
})



onMounted(async function () {
    checkData();
})

//删除数据
const del = function (index, row) {
    ElMessageBox.confirm(
        '确认删除该行数据吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //提交数据
            await easyapi.delJson('/api/register', row)
            //刷新表单数据
            tableData.value.splice(index, 1)
            if (tableData.value.length == 0) {
                checkObj.value.page = (checkObj.value.page - 1) < 1 ? 1 : checkObj.value.page - 1;
                checkData(checkObj.value.page)
            } else {
                checkData();
            }
            //提示删除成功
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

//新增数据
//显示新增窗口
const openAddWin = async function () {
    addObject.value = {}
    addWinVisible.value = true;
}
//关闭新增窗口
const closeAddWin = function () {
    addWinVisible.value = false;
}
//上次新增数据
const addSave = async function () {
    addForm.value.validate(async (valid) => {
        if (valid) {
            //保存新增的数据 addObject
            //发送请求
            let result = await easyapi.postJson('/api/register', addObject.value);
            if (result.code == 400) {
                ElMessage({
                    type: 'info',
                    message: '会员电话或教练电话错误'
                })
            } else if (result.code == 666) {
                ElMessage({
                    type: 'info',
                    message: '会员与教练已存在表中，请勿重复添加'
                })
            } else {
                //当前页行数小于size则将数据添加到该页
                if (tableData.value.length < checkObj.value.size) {
                    tableData.value.push(result.data);
                } else {
                    checkData();
                }
                //刷新表单
                //提示新增成功
                ElMessage({
                    type: 'success',
                    message: '新增数据成功',
                })
                //关闭窗口
                closeAddWin()
            }
        } else {
            ElMessage({
                type: 'info',
                message: '格式错误',
            })
        }
    })
}

//修改数据
//显示编辑窗口
const openEditWin = function () {
    editWinVisible.value = true;
}
//关闭编辑窗口
const closeEditWin = function () {
    editWinVisible.value = false;
}
//点击编辑按钮，执行的方法
const edit = function (index, row) {
    //绑定要修改的数据
    editObject.value.memberPhoneNumber = row.memberPhoneNumber;
    editObject.value.trainerPhoneNumber = row.trainerPhoneNumber;
    editObject.value.total = row.total;
    editObject.value.completed = row.completed;
    editIndex = index;
    //打开对话框
    openEditWin();
}
//保存修改编辑数据
const editSave = async () => {
    editForm.value.validate(async (valid) => {
        if (valid) {
            //发送请求
            let result = await easyapi.putJson('/api/register', editObject.value)
            //刷新表单
            tableData.value[editIndex] = result.data;
            //提示
            ElMessage({
                type: 'success',
                message: '编辑数据成功',
            })
            //关闭窗口
            closeEditWin()
        } else {
            ElMessage({
                type: 'info',
                message: '格式错误',
            })
        }
    })
}

//查询功能
const checkData = async (val) => {
    //获取当前页数
    if (typeof val == 'number') {
        checkObj.value.page = val;
    }
    //查询数据
    let result = await easyapi.getSearch('/api/register', checkObj.value)
    //更新表格中的数据
    tableData.value = result.data.list;
    total.value = result.data.count;
}

//表单验证
const addForm = ref({})
const editForm = ref({})

const addCheckRules = {
    memberPhoneNumber: [
        { required: true, message: '请输入会员手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    trainerPhoneNumber: [
        { required: true, message: '请输入教练手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    total: [
        { required: true, message: '请输入总课时', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                // 使用正则表达式检查是否为正整数  
                if (!/^\d+$/.test(value)) {
                    // 如果不是正整数，返回错误  
                    callback(new Error('总课时必须是正整数'));
                } else {
                    // 转换为数字进行比较  
                    const numValue = Number(value);
                    if (numValue < 1 || numValue > 50) {
                        // 如果数字不在1到50之间，返回错误  
                        callback(new Error('总课时必须在1到50之间'));
                    } else {
                        // 验证通过  
                        callback();
                    }
                }
            }, trigger: 'blur'
        }
    ],
    completed: [
        { required: true, message: '请输入完成课时', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                // 使用正则表达式检查是否为正整数
                if (!/^\d+$/.test(value)) {
                    // 如果不是正整数，返回错误  
                    callback(new Error('课时必须是正整数'));
                } else {
                    // 转换为数字进行比较  
                    const numValue = Number(value);
                    const numTotal = Number(addObject.value.total)
                    if (numValue < 1 || numValue > 50) {
                        // 如果数字不在1到50之间，返回错误  
                        callback(new Error('课时必须在1到50之间'));
                    } else if (numValue > numTotal) {
                        // 如果数字不在1到50之间，返回错误  
                        callback(new Error('完成课时不能大于总课时'));
                    } else {
                        // 验证通过  
                        callback();
                    }
                }
            }, trigger: 'blur'
        }
    ],
}

const editCheckRules = {
    total: [
        { required: true, message: '请输入总课时', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                // 使用正则表达式检查是否为正整数  
                if (!/^\d+$/.test(value)) {
                    // 如果不是正整数，返回错误  
                    callback(new Error('总课时必须是正整数'));
                } else {
                    // 转换为数字进行比较  
                    const numValue = Number(value);
                    if (numValue < 1 || numValue > 50) {
                        // 如果数字不在1到50之间，返回错误  
                        callback(new Error('总课时必须在1到50之间'));
                    } else {
                        // 验证通过  
                        callback();
                    }
                }
            }, trigger: 'blur'
        }
    ],
    completed: [
        { required: true, message: '请输入完成课时', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                // 使用正则表达式检查是否为正整数
                if (!/^\d+$/.test(value)) {
                    // 如果不是正整数，返回错误  
                    callback(new Error('课时必须是正整数'));
                } else {
                    // 转换为数字进行比较  
                    const numValue = Number(value);
                    const numTotal = Number(editObject.value.total)
                    if (numValue < 1 || numValue > 50) {
                        // 如果数字不在1到50之间，返回错误  
                        callback(new Error('课时必须在1到50之间'));
                    } else if (numValue > numTotal) {
                        // 如果数字不在1到50之间，返回错误  
                        callback(new Error('完成课时不能大于总课时'));
                    } else {
                        // 验证通过  
                        callback();
                    }
                }
            }, trigger: 'blur'
        }
    ]
}

</script>
<template>
    <el-input v-model="checkObj.memberName" style="width: 150px" placeholder="请输入查询的会员名" />
    <el-input v-model="checkObj.trainerName" style="width: 150px" placeholder="请输入查询的教练名" />
    <el-button type="primary" @click="checkData">查询</el-button>
    <el-button type="primary" @click="openAddWin">新增</el-button>
    <el-table :data="tableData" :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
        style="width: 100%">
        <el-table-column prop="memberName" label="会员名" />
        <el-table-column prop="memberPhoneNumber" label="会员电话" />
        <el-table-column prop="trainerName" label="教练名" />
        <el-table-column prop="trainerPhoneNumber" label="教练电话" />
        <el-table-column prop="total" label="总课时" />
        <el-table-column prop="completed" label="已上课时" />
        <el-table-column label="操作" width="180px" header-align="center">
            <template #default="scope">
                <el-button type="danger" @click="del(scope.$index, scope.row)">删除</el-button>
                <el-button type="success" @click="edit(scope.$index, scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页组件初始显示的页码 -->
    <!-- size:每页的条数 -->
    <el-pagination :page-size="checkObj.size" :current-page="checkObj.page" background layout="prev, pager, next"
        :total="total" @current-change="checkData" />


    <!--start 新增信息的弹出框 -->
    <el-dialog v-model="addWinVisible" title="新增数据" width="500">
        <el-form :model="addObject" :rules="addCheckRules" ref="addForm">
            <el-form-item label="会员电话" :label-width="80" prop="memberPhoneNumber">
                <el-input v-model="addObject.memberPhoneNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="教练电话" :label-width="80" prop="trainerPhoneNumber">
                <el-input v-model="addObject.trainerPhoneNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="总课时" :label-width="80" prop="total">
                <el-input v-model="addObject.total" autocomplete="off" />
            </el-form-item>
            <el-form-item label="完成课时" :label-width="80" prop="completed">
                <el-input v-model="addObject.completed" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeAddWin">取消</el-button>
                <el-button type="primary" @click="addSave">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--end 新增信息的弹出框 -->

    <!--start 修改信息的弹出框 -->
    <el-dialog v-model="editWinVisible" title="修改数据" width="500">
        <el-form :model="editObject" :rules="editCheckRules" ref="editForm">
            <!-- <el-form-item label="会员电话" :label-width="80">
                <el-input v-model="editObject.memberPhoneNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="教练电话" :label-width="80">
                <el-input v-model="editObject.trainerPhoneNumber" autocomplete="off" />
            </el-form-item> -->
            <el-form-item label="总课时" :label-width="80" prop="total">
                <el-input v-model="editObject.total" autocomplete="off" />
            </el-form-item>
            <el-form-item label="完成课时" :label-width="80" prop="completed">
                <el-input v-model="editObject.completed" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeEditWin">取消</el-button>
                <el-button type="primary" @click="editSave">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--end 修改信息的弹出框 -->

</template>
<style></style>